<template>
  <!--<div>-->
  <div class="contentPopup" id="zxPopup" :class="{'content-heidden':!isShow}" :style="{'width': zxPageWidth+'px'}">
    <ul id="addressList">  <!--class="aui-list"--> <!--aui-list-item -->
      <li class="borderLi" :class="{nowClass:activeIndex == index}">
          uyguysgudsguyfgsudf
      </li>
      <!--v-if="addressList && addressList.length"-->
      <li class="borderLi" :class="{nowClass:activeIndex == index}"
          v-for="(item,index) in filterAddress" :key="index"
          @click="getNow(item,index)">
        <div class="leftSpan">  <!--zxIcon-->
          <span :class="{zxIcon:item.defaultaddress == 1}">
							{{ item.defaultaddress == 1 ? "默" : ''}}
						</span>
        </div>
        <div class="middle">
          <span class="addressDetail">{{item.address}}</span>
          <span v-if="storeNow && activeIndex == index" class="storeName">{{storeNow.storeName}}</span>
        </div>

        <div class="rightSpan">
          <i class="icon njfont nj-xuanzhong" style="color: red;" v-if="activeIndex == index"></i>
        </div>
        <div style="clear: both;">

        </div>
      </li>
    </ul>
    <div id="stores_map" class="stores_map" v-show="false">

    </div>
  </div>
  <!--</div>-->
</template>

<script>
  import {mapMutations, mapGetters} from 'vuex';
  import axios from 'axios';
  import {Toast} from '../../utils/toast';
  //	import { Popup } from 'mint-ui';
  export default {
    props: {
      isShow: {
        type: Boolean,
        default: function () {
          return false
        }
      },
      shoreList: {
        type: Array,
        default: function () {
          let arr = [];
          return arr;
        }
      },
      addressList: {
        type: Array,
        default: function () {
          let arr = [];
          return arr;
        }
      },
      isHome: {
        type: Boolean,
        default: false
      }

    },
    components: {},
    computed: {
      ...mapGetters('zx', [
        "getHomeAddressNow", 'getHomeStoreNow'
      ]),
      ...mapGetters('wxh', [
        "login",
        'userInfo',
        'sessionId'
      ]),
      zxPageHeight(){
        return window.screen.height;
      },
      zxPageWidth(){
        return window.environment === "edit" ? 375 : window.screen.width;
      },
      filterAddress(){

        if (this.isHome && this.address) {
          var address = null;
          console.log(this.activeIndex, '激活的地址id');
//					this.setHomeAddressNow(this.address[this.activeIndex]);
          for (let i = 0; i < this.address.length; i++) {
            if (this.address[0].defaultaddress != 1 && this.address[i].defaultaddress == 1) {

              address = this.address[0];
              this.address[0] = this.address[i];
              this.address[i] = address;
            }
          }
          return this.address;
        }
      }
    },
    watch: {
      isShow(oldVal, newVal){
        console.log(oldVal, newVal)
      },
      userInfo(newVal, oldVal){
        if (this.isHome) {
          this.checkLogin();
        }
      }
    },
    data() {
      return {
        activeIndex: 0,
        stores: null, // 门店列表
        address: null, //地址列表
        myMap: null, // 地图对象
        lng: null,  // 当前位置的经度  或者 所选择的收获地址的经度  第一次推送默认地址
        lat: null,  // 当前位置的纬度 或者 所选择的地址的纬度  第一次推送默认地址
        showReload: false,
        storeNow: null  // 当前门店
      }
    },
    mounted(){
      if (this.isHome) {
        this.initScript();
      }

    },
    created() {
      console.log(this.isHome, '是否是首页')
      if (this.isHome) {
        this.checkLogin();
        this.storeNow = this.getHomeStoreNow;
        this.setUseMapFlag(2); // 设置状态为定位中   2
      }
//			console.log(this.shoreList,this.isShow,this.login);
    },
    beforeDestroy() {
      // 处理抖动问题
//			if(this.isHome){
//				if(document.querySelectorAll(".amap-sug-result")){
//					document.querySelector("body").removeChild(document.querySelectorAll(".amap-sug-result"));
//				}
//			}
    },
    methods: {
      ...mapMutations('zx', [
        "setHomeAddressNow", "setHomeStoreNow", "setIsShow", "setUseMapFlag"
      ]),
      getNow(item, index){
        console.log(item, index);
        this.hide();  //收起下拉
        this.activeIndex = index;
        this.lng = item.positionlng;
        this.lat = item.positionlat;
        this.setHomeAddressNow(item);
        this.getAddressDistance();
      },
      //收起下拉框
      hide(){
        this.setIsShow(false);
        if (document.getElementById('zxHomeCover')) {
          document.getElementById('zxHomeCover').remove(0);
        }
      },
      checkLogin(){
        this.getStores();
//				console.log(this.login,'用户信息');
//				console.log(this.userInfo,'用户信息');
        if (this.login) {
//					console.log('已登陸');
          this.getAddress();
        } else {
//					console.log('未登錄');
        }
      },
      //获取门店列表
      getStores(){
        var url = window.api.base_host + "/baseStore/getRestStore";
        var params = {
          enterpriseCode: window.api.enterpriseCode
        }
        var config = {
          url: url,
          methods: "GET",
          params
        }

        axios(config).then((res) => {
          console.log(res.data.data[0], '门店列表');
//					console.log(res.data.status,'状态')
          if (res.data.returnCode == 1) {
            this.stores = res.data.data[0];
          }
        })

      },
//			设置默认地址
      setDefaultAddress(params){
        if (params) {
          params.defaultaddress = 1;
          params.type = 'UPDATE'
          let config = {
            url: window.api.customer_host + '/address',
            method: 'POST',
            data: params,
            headers: {'sessionId': this.sessionId, 'Content-Type': 'application/json', 'Accept': 'application/json'},
          }
          axios(config).then((res) => {
            console.log('首页设置默认地址');
          })
        }
      },
//          获取当前门店的地址判断有无默认地址
      getNowStoreAddress(storeCode){
        var arr = [];

        if (this.address && this.address.length) {
          for (let j = 0; j < this.address.length; j++) {
            if (storeCode == this.address[j].storeCode) {
              arr.push(this.address[j]);
            }
          }
        }

        var flag = false;
        var address = arr[0];
        if (arr && arr.length) {
          for (let i = 0; i < arr.length; i++) {
            console.log("--****-----++++++****-----")
            if (arr[i].defaultaddress == 1) {
              flag = true;
            }
            if (arr[i].addressid > address.addressid) {
              address = arr[i];
            }
          }
        }
        if (!flag) {
          console.log('------*****-----')
          this.setDefaultAddress(address);
        }
      },
      //获取地址信息
      getAddress(){

        if (this.userInfo) {
          this.address = this.userInfo.addressLists;
        }
      },
      //引入高德地圖
      initScript() {
        //判断如果有script就删掉
        if (document.querySelector("#amap-box")) {
          document.body.removeChild(document.querySelector("#amap-box"));
        }
        let amapBox = document.createElement("div");
        amapBox.setAttribute("id", "amap-box");

        let script1 = document.createElement("script");
        script1.onload = () => {
          console.log("地图加载完毕");
          let script2 = document.createElement("script");
          script2.onload = () => {
            console.log("script2加载完毕");
            setTimeout(() => {
              this.initMap();
            }, 500);
          }
          script2.src = "//webapi.amap.com/ui/1.0/main.js";
          amapBox.insertAdjacentElement("beforeend", script2);
        };
        script1.src = "http://webapi.amap.com/maps?v=1.3&key=9bfe3d8b8882b7d3e4c23e43d38b18ba";
        amapBox.insertAdjacentElement("beforeend", script1);
        document.body.appendChild(amapBox);
      },
      // 创建地图对象  如果登录没登陆就定位推荐  如果登录了就
      initMap(){
        try {
          this.myMap = new AMap.Map('stores_map', {
            zoom: 16,
            center: [116.397428, 39.90923], //new AMap.LngLat(116.39,39.9)
            resizeEnable: true,
            scrollWheel: true
          });
        } catch (err) {
          if (err) {
            console.log(123456)
            this.setUseMapFlag(1);  //地图加载失败
            this.showReload = true;
//						Toast({
//							"message": "加载失败",
//							"duration": 2000,
//							"type" : "fail"
//						})
            return false
          }
        }

        if (!this.login) {
          this.getStoreDistance();
        } else {
          //登录了却没有收货地址  推送离当前位置最近的门店
          console.log(this.address, '登录获取地址')
          if (this.address == null || !this.address.length) {
            console.log(123456)
            this.setHomeAddressNow = null;
            this.getStoreDistance();
            return;
//						localStorage.removeItem('lng')
//						localStorage.removeItem('lat')
          }
          //登录了 并有地址的情况  判断是否已经推荐过了  没有推荐过就根据地址推荐最近门店

          var flagDefault = false;  // 登录了有地址有默认地址的标志
          var oldAddressFlag = false; // 原来的地址还存不存在  false表示不存在
//					for(let i = 0; i < this.address.length; i++){
//						if(this.getHomeAddressNow.addressid == this.address[i].addressid){
//							oldAddressFlag = true;
//						}
//					}

          //此处应该判断原来的那个地址存不存在  不存在了执行
          if (!this.getHomeAddressNow) {

            for (let i = 0; i < this.address.length; i++) {
              if (this.address[i].defaultaddress == 1) {
                this.lng = this.address[i].positionlng;
                this.lat = this.address[i].positionlat;
                this.activeIndex = Number(i);
                this.setHomeAddressNow(this.address[i]);
                flagDefault = true;  //登录了 却没有默认地址
              }
            }
//						console.log()
            //登录了 却没有默认地址 取地址列表的第一个地址（获取离该地址最近的门店）
            if (flagDefault == false) {
              this.lng = this.address[0].positionlng;
              this.lat = this.address[0].positionlat;
              this.activeIndex = 0;
              this.setHomeAddressNow(this.address[0]);
            }
            this.getAddressDistance();
          }

        }
      },
      //如果没登录 获取离当前位置最近的门店 先定位当前位置 展示推荐的门店
      getStoreDistance(){
        if (localStorage.getItem('lng') && localStorage.getItem('lat')) {
          this.lng = localStorage.getItem('lng');
          this.lat = localStorage.getItem('lat');
          this.getDistance(this.stores);
        } else {
          var that = this;
          this.myMap.plugin(['AMap.Geolocation', 'AMap.LngLat'], function () {

//						that.setUseMapFlag(2) ; // 定位中

            var userGeolocation = new AMap.Geolocation({
              enableHighAccuracy: true, //是否使用高精度定位，默认:true
              timeout: 10000, //超过10秒后停止定位，默认：无穷大
              maximumAge: 0 //定位结果缓存0毫秒，默认：0
            })

            console.log(userGeolocation, 'dingwei對象');

            //					console.log("8888888******")
            //					console.log(this)
            //					console.log(that.myMap,'地圖對象')
            //					debugger;
            that.myMap.addControl(userGeolocation);
            userGeolocation.getCurrentPosition();
            AMap.event.addListener(userGeolocation, 'complete', function (result) {

              that.setUseMapFlag(3); // 定位完成

              console.log(result, '定位成功返回结果');
              //存经纬度信息
              that.lng = result.position.lng;
              that.lat = result.position.lat;
              localStorage.setItem('lng', that.lng);
              localStorage.setItem('lat', that.lat);
              that.getDistance(that.stores);
            }); //返回定位信息

          })
        }

      },
      //如果登录了 计算所选地址到门店的距离
      getAddressDistance(){
        var that = this;
//				console.log(that.stores,'门店');
        this.myMap.plugin(['AMap.LngLat'], function () {
          that.getDistance(that.stores);
        });
      },
      //获取最近距离的门店
      getDistance(list){
        if (!list) {
//					console.log('没有获取到门店列表 ');
          return
        }
        console.log(this.lng, this.lat, '地址经纬度');
        var that = this;
        var minDistance = 0;
        var minDistanceItem = null;
        var lnglat = new AMap.LngLat(that.lng, that.lat);
        for (let i = 0; i < list.length; i++) {
          var arr = [];
          //兼容 以防门店经纬度为null 找不到
          if (list[i].positionLng && list[i].positionLat) {
            arr.push(list[i].positionLng);
            arr.push(list[i].positionLat);
          } else if (list[i].positionlng && list[i].positionlat) {
            arr.push(list[i].positionlng);
            arr.push(list[i].positionlat);
          } else {
            arr.push(116.397428);
            arr.push(39.90923);
          }
          //计算距离
          var myDistance = Number(lnglat.distance(arr));
          if (i == 0) {
            minDistance = myDistance;
            minDistanceItem = list[i];
          } else {
            if (minDistance > myDistance) {
              minDistance = myDistance;
              minDistanceItem = list[i];
            }
          }
        }
        that.setUseMapFlag(3);
        console.log(minDistanceItem.storeCode, '最近的一個')
        console.log(localStorage.getItem('storeCode'), minDistanceItem.storeCode, '当前门店')
        if (localStorage.getItem('storeCode') != minDistanceItem.storeCode || !this.getHomeStoreNow) {
          console.log('/-/-/-/-++', minDistanceItem)
          this.initStoreNow(minDistanceItem.storeCode, minDistanceItem.storeId);
          this.storeNow = minDistanceItem;
          this.setHomeStoreNow(minDistanceItem);
        }
      },
      //获取到最近的门店后的配置
      initStoreNow(storeCode, storeId){

        //设置localStorage
        localStorage.setItem("storeCode", storeCode);
        localStorage.setItem("storeId", storeId);
        window.api.storeCode = storeCode;
        //通知其他模块，门店切换了
        PSEvent.trigger("changeStoreCode");
        //如果当前店没有默认地址则设置一个默认地址
        if (this.login) {
          this.getNowStoreAddress(storeCode);
        }
      }
    },

  }
</script>

<style scoped="scoped">
  .contentPopup {
    /*height: 6.6rem;*/
    min-height: 70vh;
    position: absolute;
    top: 3rem;
    left: 0rem;
    width: 100%;
    transition: 0.3s;
    overflow-y: scroll;
    overflow-scrolling: auto;
    z-index: 2;
  }

  .content-heidden {
    height: 0;
  }

  .nowClass {
    background: #F2F2F2 !important;
  }

  .borderLi {
    border: 1px solid #F2F2F2;
    min-height: 2.2rem;
    line-height: 2.2rem;
    display: flex;
    border-bottom: 0;
    background: #FFFFFF;
  }

  .borderLi:first-child {
    border-top: 0;
  }

  .leftSpan {
    /*float: left;*/
    width: 10%;
    text-align: left;
    padding-left: 0.75rem;
  }

  .rightSpan {
    /*float: right;*/
    width: 10%;
    text-align: right;
    padding-right: 0.75rem;
  }

  .middle {
    /*float: left;*/
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    text-align: left;
    width: 80%;
    /*text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;*/
  }

  .addressDetail {
    width: 50%;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
    text-align: center;
  }

  .storeName {
    width: 50%;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
    text-align: center;
  }

  .zxIcon {
    font-size: 12px;
    background: #FF2600;
    padding: 0 2px;
    margin-top: 3px;
    border-radius: .2rem;
    color: white;
    height: auto;
  }

</style>
